package com.push.xu.xpush.receiver;

import java.nio.charset.Charset;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.huawei.hms.support.api.push.PushReceiver;
import com.push.xu.xpush.constant.Constant;
import com.push.xu.xpush.util.PushRepeater;
import com.push.xu.xpush.util.SPUtils;

import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;

public class HuaweiPushReceiver extends PushReceiver {

    private static final String TAG = "HuaweiPushReceiver";
    private String msg;
    
    @Override
    public void onToken(Context context, String token,Bundle bundle) {
        super.onToken(context, token);
        //save token when you call unregister method
        SPUtils.getInstance(Constant.PUSH_MESSAGE_TABLE).put("push_token", token);
        PushRepeater.transmitCommandResult(context, token,null,null);
    }

    @Override
    public void onPushState(Context context, boolean b) {
        super.onPushState(context, b);
    }

    @Override
    public void onToken(Context context, String s) {
        super.onToken(context, s);
    }

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onPushMsg(Context context, byte[] bytes, String s) {
        super.onPushMsg(context, bytes, s);
        String sByte = new String(bytes, Charset.forName("UTF-8"));
        try {
			msg = (String) new JSONObject(sByte).get("extrasStr");
		} catch (JSONException e) {
			e.printStackTrace();
		}
        PushRepeater.transmitMessage(context, null, msg, null);
    }

    @Override
    public void onEvent(Context context, Event event, Bundle bundle) {
        super.onEvent(context, event, bundle);
        int notifyId = bundle.getInt(BOUND_KEY.pushNotifyId, 0); 
        if (event == Event.NOTIFICATION_CLICK_BTN) {
        	//通知栏中通知上的按钮被点击
        } else if(event == Event.NOTIFICATION_OPENED) {
        	//通知栏中的通知被点击打开
        	if (0 != notifyId) {
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
                manager.cancel(notifyId); 
            }
        	
        	if (bundle != null) {
              try {
            	  msg = (String) new JSONArray(bundle.getString("pushMsg")).get(0);
                  PushRepeater.transmitNotificationClick(context, 0, null, null, msg, null);
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
        }
    }
}